package com.jk.service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jk.dao.OrderDao;
import com.jk.entity.Cart;
import com.jk.entity.Order;
import com.jk.entity.OrderItem;
import com.jk.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisTemplate redisTemplate;

    public List<Order> queryOrderLisr(HttpServletRequest request) {
        List<Order> list=new ArrayList<>();
        User user = (User) request.getSession().getAttribute("user");
        Gson gson = new Gson();
        HashOperations hashOperations = redisTemplate.opsForHash();
        String order = (String) hashOperations.get("order", user.getUser_id());
        list= gson.fromJson(order, new TypeToken<List<Order>>() {}.getType());
        return  list;
    }


    public List<Order> GetOrderList(HttpServletRequest request, Order order) {
        User user1 =(User) request.getSession().getAttribute("user");
        String userid = user1.getUser_id();
        List<Order> orders = orderDao.GetOrderList(order,userid);
        if(orders.size()>0){
            for (Order  order1:orders) {
                String oid = order1.getOrder_id();
                List<OrderItem> orderItems=orderDao.getOrderItem(oid);
                order1.setOrderItems(orderItems);
            }
        }
        return orders;
    }


    public void delOrderId(String[] ids) {
        orderDao.delOrderId(ids);
        orderDao.delOrderItem(ids);
    }


    public List<OrderItem> queryOrderItme(String oid) {
        return  orderDao.getOrderItem(oid);
    }
}
